<?php
namespace app\api\model;

use think\Model;

class Cart extends Base
{
    protected $table = 'cart';
    protected $autoWriteTimestamp = 'datetime';


    public function product()
    {
        return $this->hasOne('Product','id','product_id');
    }

    public function lists($token)
    {
        $user = $this->token($token);
        $num = [];
        $data = [];
        $products = $this->with(['product'])->where('user_id',$user->user_id)->select();

        foreach ($products as $product){
            $product['pruduct_price_sum'] = $product['product']['price'] *  $product['num'];
            array_push($num, $product['pruduct_price_sum']);
        }

        $price_sum = round(array_sum($num),2);
        $data['products'] = $products;
        $data['price_sum'] = $price_sum;


        return $data;


    }

    public function add($token, $param = [])
    {
        $user = $this->token($token);
        $param['user_id'] = $user->user_id;
        try {
            $product = $this->where('product_id', $param['product_id'])->find();

            if (!$product) {

                $this->create($param);

            } else {

                $this->where('product_id', $param['product_id'])->where('user_id', $param['user_id'])->update(['num' => $param['num'] + $product->num]);


            }

            $status = true;

        } catch (\Exception $e) {

            $status = false;
        }

        return $status;

    }


    public function changeCounts($data = [])
    {

        if ($data['type'] == 'cut'){
            $product = $this->where('id',$data['id'])->find();

            if ($product->num>1){
                $this->where('id',$data['id'])->update(['num'=>$product->num-1]);
                return true;
            }

            return false;
        }else{
            $cart = $this->where('id',$data['id'])->find();
            $product =  Product::where('id',$cart->product_id)->find();

            if ($cart->num<$product->stock){
                $this->where('id',$data['id'])->update(['num'=>$cart->num+1]);
                return true;
            }

            return false;

        }

    }
}